package com.koron.css2.serviceManage.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.SysModuleBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.SysModuleMapper;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.utils.RedisUtils;
import com.koron.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;



public class SysModuleAdd implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

		@SuppressWarnings("rawtypes")
		MessageBean<List> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", List.class);

//		Jedis redis = null;
		try {
			SysModuleBean bean = JsonUtils.objectToPojo(req.getData(), SysModuleBean.class);
			SysModuleMapper mapper = factory.getMapper(SysModuleMapper.class);
			bean.setModuleCode("");
			bean.setCreateName(userInfo.getUserInfo().getName());
			bean.setCreateTime(CommonUtils.getCurrentTime());
			// 当前添加的模块属于哪个模块id
			if (StringUtils.isBlank(bean.getParent())) {
				// 默认跟目录下
				bean.setParent("0");
			}
			// 生成子模块code
			handCode(mapper, bean);
			mapper.insertSysModule(bean);
//			redis = RedisUtils.getJedis();
			RedisUtils.del(Constant.SUB_MODULE);
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return info;
	}

	/**
	 * 自动生成分级code
	 * 
	 * @param mapper
	 * @param bean
	 */
	public static void handCode(SysModuleMapper mapper, SysModuleBean bean) {
		// 生成code, 规则5位一级，下级自动继承上级
		String parentCode = "";
		SysModuleBean parentBean = null;
		if (StringUtils.isNotBlank(bean.getParent() + "") && !bean.getParent().equals("0")) {
			parentBean = mapper.getSysMonduleById(bean.getParent());
			parentCode = parentBean.getModuleCode();
		}
		// 取父级目录下最大的下级目录
		String maxCode = mapper.selectMaxModuleCode(parentCode);
		if (StringUtils.isBlank(maxCode)) {// 如果未找到，说明下面没有子级，给初始值
			maxCode = parentCode + "000";
		}
		// 未位加1
		long last5 = Long.parseLong("1" + maxCode.substring(maxCode.length() - 3)) + 1;
		maxCode = maxCode.substring(0, maxCode.length() - 3) + (last5 + "").substring(1);

		// 重设code
		bean.setModuleCode(maxCode);
		bean.setLeaf(1);// 新增加的数据，都是叶结点

		// 自动更新其上级为目录
		if (parentBean != null) {
			parentBean.setLeaf(0);
			mapper.updateSysMondule(parentBean);
			bean.setModuleLevel(parentBean.getModuleLevel() + 1);// 父节点+1
			bean.setSystemCode(parentBean.getSystemCode());
		} else {
			bean.setModuleLevel(1);// 新节点
		}
	}
}
